<template>
  <div class="prdp-outer">
    <div class="prdp-main">
      <!-- 头部标题和状态指示器 -->
      <div class="prdp-title-bar">
        <h2>连退原料质量分析</h2>
        <div class="prdp-status-indicators">
          <div class="prdp-status-item">
            <span class="prdp-status-text">打滑</span>
            <span class="prdp-status-dot"></span>
          </div>
          <div class="prdp-status-item">
            <span class="prdp-status-text">碰撞</span>
            <span class="prdp-status-dot"></span>
          </div>
          <div class="prdp-status-item">
            <span class="prdp-status-text">性能分析</span>
            <span class="prdp-status-dot"></span>
          </div>
        </div>
      </div>
      <!-- 搜索区域 -->
      <div class="prdp-search-container">
        <el-form :inline="true" class="prdp-search-form">
          <el-form-item label="入口卷号">
            <el-input v-model="searchInput" placeholder="请输入查询内容"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
            <el-button type="success" @click="handleExport">导出</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 数据表格 -->
      <div class="prdp-table-container">
        <el-table :data="tableData" border style="width: 100%" :header-cell-style="headerStyle" height="100%">
          <el-table-column prop="steelGrade" label="钢种" width="100">
            <template #default="scope">
              <span>{{ scope.row.steelGrade === 0 ? 0 : scope.row.steelGrade ?? '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="planNo" label="计划号" width="100">
            <template #default="scope">
              <span>{{ scope.row.planNo === 0 ? 0 : scope.row.planNo ?? '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="inMatNo" label="入口卷号" width="150">
            <template #default="scope">
              <span>{{ scope.row.inMatNo === 0 ? 0 : scope.row.inMatNo ?? '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="inMatWidth" label="入口材料宽度(mm)" width="150">
            <template #default="scope">
              <span>{{ scope.row.inMatWidth === 0 ? 0 : scope.row.inMatWidth ?? '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="inMatThick" label="入口材料厚度(mm)" width="150">
            <template #default="scope">
              <span>{{ scope.row.inMatThick === 0 ? 0 : scope.row.inMatThick ?? '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="inMatLen" label="入口材料长度(m)" width="140">
            <template #default="scope">
              <span>{{ scope.row.inMatLen === 0 ? 0 : scope.row.inMatLen ?? '-' }}</span>
            </template>
          </el-table-column>

          <!-- 板形情况多级表头 -->
          <el-table-column label="板形情况" align="center">
            <el-table-column prop="ascHeadJifen" label="头部" width="100" align="center">
              <template #default="scope">
                <el-tooltip
                  v-if="scope.row.ascHeadJifen !== null && scope.row.ascHeadJifen !== undefined && !isNaN(scope.row.ascHeadJifen)"
                  :content="`当前值: ${scope.row.ascHeadJifen}`"
                  placement="top"
                >
                  <span :class="getGradeClassByScore(scope.row.ascHeadJifen)" class="grade-dot">
                    <span class="grade-letter">{{ getGradeLetterByScore(scope.row.ascHeadJifen) }}</span>
                    <span class="grade-circle">●</span>
                  </span>
                </el-tooltip>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="ascMidJifen" label="中部" width="100" align="center">
              <template #default="scope">
                <el-tooltip
                  v-if="scope.row.ascMidJifen !== null && scope.row.ascMidJifen !== undefined && !isNaN(scope.row.ascMidJifen)"
                  :content="`当前值: ${scope.row.ascMidJifen}`"
                  placement="top"
                >
                  <span :class="getGradeClassByScore(scope.row.ascMidJifen)" class="grade-dot">
                    <span class="grade-letter">{{ getGradeLetterByScore(scope.row.ascMidJifen) }}</span>
                    <span class="grade-circle">●</span>
                  </span>
                </el-tooltip>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="ascTailJifen" label="尾部" width="100" align="center">
              <template #default="scope">
                <el-tooltip
                  v-if="scope.row.ascTailJifen !== null && scope.row.ascTailJifen !== undefined && !isNaN(scope.row.ascTailJifen)"
                  :content="`当前值: ${scope.row.ascTailJifen}`"
                  placement="top"
                >
                  <span :class="getGradeClassByScore(scope.row.ascTailJifen)" class="grade-dot">
                    <span class="grade-letter">{{ getGradeLetterByScore(scope.row.ascTailJifen) }}</span>
                    <span class="grade-circle">●</span>
                  </span>
                </el-tooltip>
                <span v-else>-</span>
              </template>
            </el-table-column>
          </el-table-column>

          <el-table-column prop="paopianRate" label="预测跑偏概率" width="120" align="center">
            <template #default="scope">
              <el-tooltip
                v-if="!isNaN(scope.row.paopianRate * 100)"
                :content="`预测跑偏概率: ${(scope.row.paopianRate * 100).toFixed(0)}%`"
                placement="top"
              >
                <span class="rate-container">
                  <span :class="['rate-dot', scope.row.paopianRate * 100 > 50 ? 'rate-dot-red' : 'rate-dot-green']">●</span>
                  <span class="rate-text">{{ (scope.row.paopianRate * 100).toFixed(0) }}%</span>
                </span>
              </el-tooltip>
              <span v-else>-</span>
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="scope">
              {{ formatISODate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="showDetail(scope.row)">查看</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="prdp-pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalItems"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 详情弹窗 -->
      <el-dialog
        v-model="detailDialogVisible"
        :title="`出口卷号：${currentDetail.outboundNo}`"
        width="80%"
        class="prdp-detail-dialog"
        destroy-on-close
        @closed="handleDialogClose"
      >
        <div class="prdp-detail-container">
          <!-- 钢卷基本信息 -->
          <div class="prdp-coil-info">
            <el-descriptions :column="6" border>
              <el-descriptions-item label="计划号" width="150px">{{ currentDetail.planContent }}</el-descriptions-item>
              <el-descriptions-item label="冷轧卷号" width="150px">{{ currentDetail.inboundNo }}</el-descriptions-item>
              <el-descriptions-item label="连退卷号" width="150px">{{ currentDetail.outboundNo }}</el-descriptions-item>
              <el-descriptions-item label="热卷号" width="150px">{{ currentDetail.coilNo }}</el-descriptions-item>
              <el-descriptions-item label="C" width="100px">0.0784</el-descriptions-item>
              <el-descriptions-item label="Si" width="100px">0.1272</el-descriptions-item>
              <el-descriptions-item label="Mn" width="100px">0.5207</el-descriptions-item>
              <el-descriptions-item label="P" width="100px">0.01935</el-descriptions-item>
              <el-descriptions-item label="S" width="100px">0.00378</el-descriptions-item>
              <el-descriptions-item label="板形预开始时间" width="180px">2024-03-05 00:59:42</el-descriptions-item>
              <el-descriptions-item label="板形预结束时间" width="180px">2024-03-05 01:05:17</el-descriptions-item>
              <el-descriptions-item label="记录时间" width="180px">2024-03-05 06:06:24</el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 图表区域 -->
          <div class="prdp-charts-container">
            <div class="prdp-charts-row">
              <div class="prdp-chart-item">
                <div class="prdp-chart-title">5机架张力差</div>
                <div class="prdp-chart" id="app_tension"></div>
              </div>
              <div class="prdp-chart-item">
                <div class="prdp-chart-title">速度-长度序列(m/min)</div>
                <div class="prdp-chart" id="app11"></div>
              </div>
            </div>

            <div class="prdp-charts-row">
              <div class="prdp-chart-item">
                <div class="prdp-chart-title">5机架轧制力差</div>
                <div class="prdp-chart" id="app5"></div>
              </div>
              <div class="prdp-chart-item">
                <div class="prdp-chart-title">S5机架倾斜</div>
                <div class="prdp-chart" id="app_tilt"></div>
              </div>
            </div>
          </div>

          <!-- 板形2D/3D视图 -->
          <div class="prdp-shape-view">
            <div class="prdp-shape-tabs">
              <div class="prdp-shape-tab prdp-shape-tab-active">板形仪通道号(长度序列)</div>
              <div class="prdp-shape-tab">带钢板形3D图</div>
            </div>
            <div class="prdp-shape-content">
              <div id="app7" style="width: 100%; height: 350px"></div>
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, onUnmounted, nextTick, onBeforeUnmount } from 'vue';
  import { ElMessage } from 'element-plus';
  import * as echarts from 'echarts/core';
  import { LineChart } from 'echarts/charts';
  import { TitleComponent, TooltipComponent, GridComponent, LegendComponent, MarkLineComponent } from 'echarts/components';
  import { CanvasRenderer } from 'echarts/renderers';
  import { continuousrefund2150Api } from '/@/api/continuousrefund/continuousrefund2150';
  import { historyApi } from '/@/api/furnaceTempDynamicCtrl/history';
  // 注册ECharts组件
  echarts.use([TitleComponent, TooltipComponent, GridComponent, LegendComponent, LineChart, CanvasRenderer, MarkLineComponent]);
  // 搜索相关
  const searchInput = ref('');

  // 分页相关
  const currentPage = ref(1);
  const pageSize = ref(20);
  const totalItems = ref(0);

  // 表头样式
  const headerStyle = {
    background: '#f5f7fa',
    color: '#333',
  };

  // 详情弹窗
  const detailDialogVisible = ref(false);
  const currentDetail = reactive({
    orderNo: '',
    productPlanNo: '',
    planContent: '',
    coilNo: '',
    inboundNo: '',
    outboundNo: '',
    steelGrade: '',
    exportRollNo: '',
  });

  // 添加与LayOutJudge.vue相同的变量
  const currentRow = ref();
  const plateCurveData = ref([]);
  let rememberA: any = [];
  let rememberB: any = [];
  let rememberC: any = [];
  let rememberR: any = [];
  let clickChanel = 13;
  let formData = '';

  const tableData = ref<any[]>([]);
  let timer: any = null;

  // === 参考LayOutJudge.vue，补充全局变量定义 ===
  let toolbox = {
    iconStyle: {
      borderColor: '#222',
    },
    feature: {
      dataView: {
        show: true,
        lang: ['数据视图', '关闭', '导出Excel'],
        optionToContent: function (opt: any) {
          var axisData = opt.xAxis[0].data;
          var txisData = opt.series[0].data;
          var series = opt.series;
          var tdHeads = '<td  style="padding: 0 10px"></td>';
          var tdBodys = '';
          var nameData = txisData;
          for (var i = 0; i < nameData.length; i++) {
            tdHeads += '<td style="padding: 0 10px">' + nameData[i] + '</ td >';
          }
          var table =
            '<table id="Mytable" border="1" class="table table-bordered table-striped table-hover" style="width:100%;text-align:center;color: #000;" ><tbody><tr>' +
            tdHeads +
            ' </tr>';
          for (var i = 0, l = axisData.length; i < l; i++) {
            for (var j = 0; j < series.length; j++) {
              if (series[j].data != undefined) {
                var temp = series[j].data[i];
                if (temp != null && temp != undefined) {
                  tdBodys += '<td>' + temp + '</td>';
                } else {
                  tdBodys += '<td></td>';
                }
              }
            }
            table += '<tr><td style="padding: 0 10px">' + axisData[i] + '</td>' + tdBodys + '</tr>';
            tdBodys = '';
          }
          table += '</tbody></table>';
          return table;
        },
        contentToOption: function (HTMLDomElement: any, opt: any) {
          // 这里可根据需要实现导出Excel等功能
          return '';
        },
      },
      magicType: { show: true },
      restore: { show: true },
      saveAsImage: { show: true },
    },
  };
  let sum = 1;
  let dialogVisible2 = { value: false };
  let dialogTitle2 = { value: '' };

  const fetchData = async () => {
    // 未输入卷号时，不传入 inMatNo，仅带分页参数
    const params: any = {
      pageIndex: String(currentPage.value || 1),
      pageSize: String(pageSize.value || 30),
    };
    if (searchInput.value) {
      params.inMatNo = String(searchInput.value);
    }
    const res = await continuousrefund2150Api.getRunTrackData(params);
    const list = Array.isArray(res?.data?.data) ? res.data.data : Array.isArray(res?.data?.data?.list) ? res.data.data.list : [];
    if (Array.isArray(list)) {
      tableData.value = list.map((item: any) => ({
        steelGrade: item.steelGrade ?? item.steelRrade ?? '-',
        planNo: item.planNo ?? '-',
        inMatNo: item.inMatNo ?? '-',
        inMatWidth: item.inMatWidth ?? null,
        inMatThick: item.inMatThick ?? null,
        inMatLen: item.inMatLen ?? null,
        ypClass: item.ypClass ?? null,
        exWidthClass: item.exWidthClass ?? null,
        exThkClass: item.exThkClass ?? null,
        ascHeadJifen: item.ascHeadJifen ?? null,
        ascMidJifen: item.ascMidJifen ?? null,
        ascTailJifen: item.ascTailJifen ?? null,
        ascDesc: item.ascDesc ?? '-',
        paopianRate: item.paopianRate ?? null,
        createTime: item.createTime ?? null,
      }));
      // 使用后端返回的 count 作为总数（优先级最高），兼容其他位置
      totalItems.value = (res?.data?.count ?? res?.data?.data?.total ?? res?.data?.total ?? list.length) as number;
    } else {
      tableData.value = [];
      totalItems.value = (res?.data?.count ?? res?.data?.data?.total ?? res?.data?.total ?? 0) as number;
    }
  };

  const handleSearchData = async () => {
    await fetchData();
  };

  const startPolling = () => {};
  const stopPolling = () => {};

  onMounted(() => {
    // 进入页面默认查询一次（不传 inMatNo）
    fetchData();
  });
  onUnmounted(() => {
    stopPolling();
  });

  const handleSearch = () => {
    handleSearchData();
  };

  function formatISODate(input: any): string {
    if (input === null || input === undefined || input === '') return '-';
    let ts: number | null = null;
    if (typeof input === 'number') {
      ts = input > 1e12 ? input : input * 1000;
    } else if (typeof input === 'string') {
      const n = Number(input);
      if (!Number.isNaN(n)) {
        ts = n > 1e12 ? n : n * 1000;
      } else {
        const d = new Date(input);
        ts = isNaN(d.getTime()) ? null : d.getTime();
      }
    } else if (input instanceof Date) {
      ts = input.getTime();
    }
    if (ts === null) return '-';
    const date = new Date(ts);

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
    const day = String(date.getDate()).padStart(2, '0');

    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }

  // 处理重置事件
  const handleReset = () => {
    searchInput.value = '';
    tableData.value = [];
    ElMessage.info('重置搜索条件');
  };

  // 处理导出事件
  const handleExport = () => {
    ElMessage.success('数据导出成功');
  };

  // 处理分页大小变化
  const handleSizeChange = (size: number) => {
    pageSize.value = size;
    currentPage.value = 1;
    fetchData();
  };

  // 处理页码变化
  const handleCurrentChange = (page: number) => {
    currentPage.value = page;
    fetchData();
  };

  // 根据等级获取样式类
  // const getGradeClass = (grade: string) => {
  //   switch (grade) {
  //     case 'A': return 'prdp-grade-a'
  //     case 'B': return 'prdp-grade-b'
  //     case 'C': return 'prdp-grade-c'
  //     case 'D': return 'prdp-grade-d'
  //     default: return ''
  //   }
  // }

  // 修改显示详情函数，确保每次打开弹窗时都重新初始化图表
  const showDetail = (row: any) => {
    Object.assign(currentDetail, row);
    currentRow.value = row;
    formData = row.inMatNo; // 入口卷号
    disposeCharts();
    detailDialogVisible.value = true;
    nextTick(() => {
      findAll2(row.inMatNo);
      findTensionChart(row.inMatNo);
      findAll4(row.inMatNo, row);
      findAll4_1(row.inMatNo);
    });
  };

  // 添加与LayOutJudge.vue相同的接口调用函数
  async function findAll2(extid: any) {
    let params = ['flat_ave_positive', 'flat_ave'];

    const graphParam = {
      line: 'TCM2280',
      extid: [extid],
      curve: params,
    };
    const response = await historyApi.getgraphData(graphParam);
    if (response.data.data.curve[0]) {
      echart_test4(response.data.data.curve[0]);
    }
  }

  async function findAll4(extid: any, row: any) {
    let params = [
      'tcm_shape_channe_0',
      'tcm_shape_channe_1',
      'tcm_shape_channe_2',
      'tcm_shape_channe_4',
      'tcm_shape_channe_5',
      'tcm_shape_channe_6',
      'tcm_shape_channe_7',
      'tcm_shape_channe_8',
      'tcm_shape_channe_9',
      'tcm_shape_channe_10',
      'tcm_shape_channe_11',
      'tcm_shape_channe_12',
      'tcm_shape_channe_13',
      'tcm_shape_channe_14',
      'tcm_shape_channe_15',
      'tcm_shape_channe_16',
      'tcm_shape_channe_17',
      'tcm_shape_channe_18',
      'tcm_shape_channe_19',
      'tcm_shape_channe_20',
      'tcm_shape_channe_21',
      'tcm_shape_channe_22',
      'tcm_shape_channe_23',
      'tcm_shape_channe_24',
      'tcm_shape_channe_25',
      'tcm_shape_channe_26',
      'tcm_shape_channe_27',
      'tcm_shape_channe_28',
      'tcm_shape_channe_29',
      'tcm_shape_channe_30',
      'tcm_shape_channe_31',
      'tcm_shape_channe_32',
      'tcm_shape_channe_33',
      'tcm_shape_channe_34',
      'tcm_shape_channe_35',
      'tcm_shape_channe_36',
      'tcm_shape_channe_37',
      'tcm_shape_channe_38',
      'tcm_shape_channe_39',
      'tcm_shape_channe_40',
      'tcm_shape_channe_41',
      'tcm_shape_channe_42',
      'tcm_shape_channe_43',
      'tcm_shape_channe_44',
      'tcm_shape_channe_45',
      'tcm_shape_channe_46',
      'tcm_shape_channe_47',
      'tcm_shape_channe_48',
      'tcm_shape_channe_49',
      'tcm_shape_channe_50',
      'tcm_shape_channe_51',
      'tcm_shape_channe_52',
      'tcm_shape_channe_53',
      'tcm_shape_channe_54',
      'tcm_shape_channe_55',
      'tcm_shape_channe_56',
      'tcm_shape_channe_57',
      'tcm_shape_channe_58',
      'tcm_shape_channe_59',
      'tcm_shape_channe_60',
      'tcm_shape_channe_61',
      'tcm_shape_channe_62',
      'tcm_shape_channe_63',
      'tcm_s5_strip_speed_act',
    ];

    const graphParam = {
      line: 'TCM2280',
      extid: [extid],
      curve: params,
    };
    const response = await historyApi.getgraphData(graphParam);
    //绘制2D板形图曲线-长度序列
    if (response.data.data.curve[0].tcm_shape_channe_32) {
      let filteredObj = [];

      const newItem = Object.fromEntries(
        Object.entries(response.data.data.curve[0]).filter(([key, value]) => {
          if (Array.isArray(value)) {
            value.some((num: any) => num !== 0);
          }
          return value;
        })
      );
      filteredObj.push({ ...newItem });

      console.log('filteredObj' + filteredObj);

      echart_test7(filteredObj);
      plateCurveData.value = response.data.data.curve[0];
    } else {
      plateCurveData.value = [];
      echarts_no('app7');
      echarts_no('app9');
    }
    //绘制S5出口厚度和速度曲线-长度序列
    if (!response.data.data.curve[0].tcm_s5_strip_speed_act) {
      echarts_no('app11', 200);
    } else {
      echart_test11(response.data.data.curve[0].tcm_s5_strip_speed_act);
    }

    // 渲染tcm_shape_channe_13
    find_singleChanel(extid, 13);
  }

  async function findAll4_1(extid: any) {
    let search_group = '';
    if (currentRow.value.length > 6000) {
      search_group = 'array';
    } else {
      search_group = 'curve';
    }
    let params = ['tcm_s5_force_diff', 'tcm_s4s5_ten_diff', 'tcm_s5_tilt_act'];

    const graphParam = {
      line: 'TCM2280',
      extid: [extid],
      curve: params,
    };
    const res = await historyApi.getgraphData(graphParam);
    echart_test5(res.data.data.curve);
    echart_tilt(res.data.data.curve);
  }

  // 恢复app4区域渲染逻辑，完全对齐LayOutJudge.vue
  function echart_test4(obj: any) {
    // 如果无数据，使用假数据
    let fakeArr = Array.from({ length: 20 }, (_, i) => i + Math.random());
    let flat_ave = Array.isArray(obj.flat_ave) && obj.flat_ave.length > 0 ? obj.flat_ave : fakeArr;
    let flat_ave_positive =
      Array.isArray(obj.flat_ave_positive) && obj.flat_ave_positive.length > 0 ? obj.flat_ave_positive : fakeArr.map((v) => v + 2);
    var arrlength = [];
    for (let i = 1; i <= flat_ave.length; i++) {
      arrlength.push(i);
    }
    var myChart = echarts.init(document.getElementById('app4'));
    var option4 = {
      title: {
        text: '板形截面IU均值曲线',
        textStyle: {
          fontSize: 14,
          color: '#222',
          fontStyle: 'normal',
          fontWeight: 'bold',
        },
      },
      tooltip: { trigger: 'axis' },
      grid: { left: '3%', right: '6%', bottom: '8%', containLabel: true },
      legend: {
        x: 'center',
        data: ['板形截面IU均值曲线', '板形截面IU正值'],
        textStyle: { fontSize: 12, color: '#222' },
        icon: 'roundRect',
      },
      toolbox: toolbox,
      dataZoom: [
        { type: 'slider', show: true, xAxisIndex: [0], start: 0, end: 100 },
        { type: 'inside', xAxisIndex: [0], start: 0, end: 100 },
      ],
      xAxis: {
        type: 'category',
        boundaryGap: false,
        axisLabel: { show: true, color: '#222', fontSize: 14 },
        axisLine: { lineStyle: { color: '#222' } },
        splitLine: { show: true, lineStyle: { type: 'dotted' } },
        data: arrlength,
      },
      yAxis: {
        name: '单位:IU',
        type: 'value',
        scale: true,
        min: -10,
        max: 30,
        splitLine: { show: true, lineStyle: { type: 'dotted' } },
        axisLabel: { formatter: '{value}', color: '#222', fontSize: 14 },
        axisLine: { lineStyle: { color: '#222' } },
      },
      series: [
        {
          name: '板形截面IU均值曲线',
          type: 'line',
          smooth: true,
          data: flat_ave,
        },
        {
          name: '板形截面IU正值',
          type: 'line',
          smooth: true,
          data: flat_ave_positive,
        },
      ],
    };
    myChart.clear();
    myChart.setOption(option4);
  }

  //酸轧生产过程追溯
  function echart_test5(datas3: any) {
    let need_x11: number[] = [];
    var name1 = '5机架轧制力差';
    var need_y11 = [];
    if (Array.isArray(datas3[0].tcm_s5_force_diff) && datas3[0].tcm_s5_force_diff.length > 0) {
      need_y11 = datas3[0].tcm_s5_force_diff;
      for (let i = 0; i < datas3[0].tcm_s5_force_diff.length; i++) {
        need_x11.push(i + 1);
      }
    }
    var myChart = echarts.init(document.getElementById('app5')); //将配置注入到html中定义的容器
    var option = {
      title: {
        text: '5机架轧制力差',
        textStyle: {
          fontSize: 16,
          fontWeight: 700,
          color: '#222',
        },
      },
      legend: {
        x: 'center',
        textStyle: {
          fontSize: 12,
          color: '#222',
        },
        icon: 'roundRect',
        data: [name1],
      },
      tooltip: {
        trigger: 'axis',
        textStyle: {
          color: '#222',
          fontSize: 14,
        },
      },
      grid: {
        left: '1%',
        right: '5%',
        bottom: '6%',
        containLabel: true,
      },
      dataZoom: [
        {
          type: 'inside',
          xAxisIndex: [0],
        },
        {
          type: 'inside',
          yAxisIndex: [0],
        },
      ],
      xAxis: {
        axisLine: {
          lineStyle: {
            color: '#888',
          },
        },
        nameTextStyle: {
          fontSize: 14,
          color: '#222',
        },
        name: '(m)',
        type: 'category',
        data: need_x11,
        axisLabel: {
          color: '#222',
          fontSize: 14,
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dotted',
            color: '#ccc',
          },
        },
      },
      yAxis: [
        {
          scale: true, //纵坐标自适应
          show: true,
          axisLine: {
            lineStyle: {
              color: '#888',
            },
          },
          nameTextStyle: {
            fontSize: 14,
            padding: [0, 0, 0, 20],
            color: '#222',
          },
          boundaryGap: [0, '50%'],
          type: 'value',
          name: name1,
          position: 'left',
          splitNumber: 10,
          axisLabel: {
            formatter: '{value}',
            textStyle: {
              color: '#222',
              fontSize: 14,
            },
          },
          splitLine: {
            show: false,
          },
        },
      ],
      series: [
        {
          name: name1,
          type: 'line',
          step: 'middle',
          data: need_y11,
          yAxisIndex: 0,
          itemStyle: { color: '#67c23a' }, // 绿色
          lineStyle: { color: '#67c23a' },
        },
      ],
    };
    myChart.clear();
    myChart.setOption(option);
  }

  //酸轧生产过程追溯
  function echart_tilt(data: any) {
    var need_x11 = [];
    var need_y11 = [];
    if (Array.isArray(data[0].tcm_s5_tilt_act) && data[0].tcm_s5_tilt_act.length > 0) {
      need_y11 = data[0].tcm_s5_tilt_act;
      for (let i = 0; i <= data[0].tcm_s5_tilt_act.length; i++) {
        need_x11.push(i + 1);
      }
    }
    var myChart = echarts.init(document.getElementById('app_tilt')); //将配置注入到html中定义的容器
    var option = {
      title: {
        text: 'S5机架倾斜',
        textStyle: {
          fontSize: 16,
          fontWeight: 700,
          color: '#222',
        },
      },
      legend: {
        x: 'center', //可设定图例在左、右、居
        textStyle: {
          fontSize: 14,
          color: '#222',
        },
        icon: 'roundRect',
      },
      dataZoom: [
        {
          type: 'slider', //滑动条
          show: true, //开启
          xAxisIndex: [0],
          start: 0, //初始化时，滑动条宽度开始标度
          end: 100, //初始化时，滑动条宽度结束标度
        }, //X轴内置滑动
        {
          type: 'inside', //内置滑动，随鼠标滚轮展示
          xAxisIndex: [0],
          start: 0, //初始化时，滑动条宽度开始标度
          end: 100, //初始化时，滑动条宽度结束标度
        },
      ],
      tooltip: {
        trigger: 'axis',
        textStyle: {
          color: '#222',
          fontSize: 14,
        },
      },
      grid: {
        left: '3%',
        right: '8%',
        bottom: '6%',
        containLabel: true,
      },
      xAxis: {
        axisLine: {
          lineStyle: {
            color: '#888',
          },
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dotted',
            color: '#ccc',
          },
        },
        nameTextStyle: {
          fontSize: 14,
          color: '#222',
        },
        name: '(m)',
        type: 'category',
        data: need_x11,
        axisLabel: {
          color: '#222',
          fontSize: 14,
        },
      },
      yAxis: [
        {
          scale: true, //纵坐标自适应
          axisLine: {
            lineStyle: {
              color: '#888',
            },
          },
          type: 'value',
          name: 'mm',
          axisLabel: {
            formatter: '{value}',
            textStyle: {
              color: '#222',
              fontSize: 14,
            },
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dotted',
              color: '#ccc',
            },
          },
        },
      ],
      series: [
        {
          name: '',
          type: 'line',
          data: need_y11,
        },
      ],
    };
    myChart.clear();
    myChart.setOption(option);
  }

  // 板形2D（长度序列）
  function echart_test7(datas10: any) {
    let fakeArr = Array.from({ length: 20 }, (_, i) => Array.from({ length: 64 }, () => Math.random() * 10 - 5));
    let dataObj = datas10 && datas10[0] && Object.keys(datas10[0]).length > 0 ? datas10[0] : null;
    let res: any[] = [];
    let max = 0;
    let need_x11: number[] = [];
    if (dataObj) {
      Object.entries(dataObj).forEach(([key, value]) => {
        const macthReq = /tcm_shape_channe_(\d+)$/.exec(key);
        if (!macthReq || (Array.isArray(value) && value.every((i: any) => i === 0))) return;
        const index = Number(macthReq[1]);
        max = Math.max(max, index);
        if (Array.isArray(value)) {
          value.forEach((v: any, i: any) => {
            res.push([i, index - 1, v]);
            if (need_x11.length < value.length) {
              need_x11.push(i + 1);
            }
          });
        }
      });
    } else {
      // 用假数据
      for (let ch = 0; ch < 64; ch++) {
        for (let i = 0; i < 20; i++) {
          res.push([i, ch, fakeArr[i][ch]]);
        }
      }
      need_x11 = Array.from({ length: 20 }, (_, i) => i + 1);
      max = 63;
    }
    let Tuglie = [];
    for (var x = 0; x < res.length; x++) {
      if (res[x][0] == 1) {
        Tuglie.push(res[x]);
      }
    }
    let list: any = [];
    list = Tuglie.sort((a, b) => a[1] - b[1])
      .map((item) => item[2])
      .join(',');
    var myChart = echarts.init(document.getElementById('app7'));
    let days = [
      'c_0',
      'c_1',
      'c_2',
      'c_3',
      'c_4',
      'c_5',
      'c_6',
      'c_7',
      'c_8',
      'c_9',
      'c_10',
      'c_11',
      'c_12',
      'c_13',
      'c_14',
      'c_15',
      'c_16',
      'c_17',
      'c_18',
      'c_19',
      'c_20',
      'c_21',
      'c_22',
      'c_23',
      'c_24',
      'c_25',
      'c_26',
      'c_27',
      'c_28',
      'c_29',
      'c_30',
      'c_31',
      'c_32',
      'c_33',
      'c_34',
      'c_35',
      'c_36',
      'c_37',
      'c_38',
      'c_39',
      'c_40',
      'c_41',
      'c_42',
      'c_43',
      'c_44',
      'c_45',
      'c_46',
      'c_47',
      'c_48',
      'c_49',
      'c_50',
      'c_51',
      'c_52',
      'c_53',
      'c_54',
      'c_55',
      'c_56',
      'c_57',
      'c_58',
      'c_59',
      'c_60',
      'c_61',
      'c_62',
      'c_63',
    ];
    let listMxsMin = days.length - max;
    let a1: any = [];
    for (var i = 0; i < listMxsMin; i++) {
      a1.push('0.00');
    }
    var option = {
      title: {
        text: '板形仪通道号(长度序列)' + (currentDetail.exportRollNo || 'DEMO'),
        textStyle: {
          color: '#222',
          fontStyle: 'normal',
          fontWeight: 'bold',
          fontFamily: 'sans-serif',
          fontSize: 16,
        },
      },
      tooltip: {
        position: 'top',
        textStyle: {
          color: '#222',
          fontSize: 14,
        },
      },
      grid: {
        left: '3%',
        right: '6%',
        containLabel: true,
      },
      xAxis: {
        axisLine: {
          lineStyle: {
            color: '#888',
            width: 1,
          },
        },
        name: '(m)',
        nameTextStyle: {
          fontSize: 14,
          color: '#222',
        },
        type: 'category',
        data: need_x11,
        axisLabel: {
          color: '#222',
          fontSize: 14,
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dotted',
            color: '#ccc',
          },
        },
      },
      yAxis: {
        axisLine: {
          lineStyle: {
            color: '#888',
            width: 1,
          },
        },
        nameTextStyle: {
          fontSize: 12,
          color: '#222',
        },
        type: 'category',
        data: days,
        axisLabel: {
          color: '#222',
          fontSize: 14,
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dotted',
            color: '#ccc',
          },
        },
      },
      legend: {
        left: 'center',
        textStyle: {
          fontSize: 16,
          color: '#222',
        },
      },
      visualMap: {
        min: -25,
        max: 25,
        calculable: true,
        orient: 'vertical',
        left: 'right',
        top: 'center',
        realtime: false,
        textStyle: {
          color: '#222',
          fontSize: 14,
        },
        inRange: {
          color: [
            'RGB(0,10,255)',
            'RGB(0,150,255)',
            'RGB(0,199,255)',
            '#11fff9',
            'RGB(0,255,0)',
            '#FFF500',
            'RGB(255,230,0)',
            'RGB(249, 102, 72)',
            'RGB(255,0,0)',
          ],
        },
      },
      series: [
        {
          pointSize: 10,
          type: 'heatmap',
          data: res.sort((a: any, b: any) => a[0] - b[0]),
        },
      ],
    };
    myChart.clear();
    myChart.setOption(option, true);
  }

  //长度序列速度
  function echart_test11(datas3: any) {
    let fakeArr = Array.from({ length: 20 }, (_, i) => 10 + i * 2 + Math.random());
    let arr = Array.isArray(datas3) && datas3.length > 0 ? datas3 : fakeArr;
    var need_x11 = [];
    var need_y = [];
    for (let i = 0; i < arr.length; i++) {
      need_x11.push(i + 1);
      need_y.push(Math.floor(arr[i] * 100) / 100);
    }
    var myChart = echarts.init(document.getElementById('app11'));
    var option = {
      title: {
        text: '速度-长度序列(m/min)',
        textStyle: {
          color: '#222',
          fontSize: 16,
        },
      },
      tooltip: {
        trigger: 'axis',
        textStyle: {
          color: '#222',
          fontSize: 14,
        },
      },
      grid: {
        left: '3%',
        right: '5%',
        top: '15%',
        bottom: '18%',
        containLabel: true,
      },
      dataZoom: [
        {
          type: 'slider',
          show: true,
          xAxisIndex: [0],
          start: 0,
          end: 100,
        },
        {
          type: 'inside',
          xAxisIndex: [0],
          start: 0,
          end: 100,
        },
      ],
      xAxis: {
        type: 'category',
        boundaryGap: false,
        axisLabel: {
          color: '#222',
          fontSize: 14,
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dotted',
            color: '#ccc',
          },
        },
        axisLine: {
          lineStyle: {
            color: '#888',
          },
        },
        name: '(m)',
        data: need_x11,
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          color: '#222',
          fontSize: 14,
        },
        scale: true,
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dotted',
            color: '#ccc',
          },
        },
        axisLine: {
          lineStyle: {
            color: '#888',
          },
        },
      },
      series: {
        name: '速度',
        type: 'line',
        step: 'start',
        data: need_y,
      },
    };
    myChart.setOption(option);
  }

  // 板形长度序列曲线
  async function find_singleChanel(extid: any, chanel: any) {
    if (chanel <= 0 || chanel > 26) {
      return;
    }
    let chanel_f = [];
    chanel_f.push('tcm_shape_channe_' + chanel);
    let str = 'tcm_shape_channe_' + chanel;

    const graphParam = {
      line: 'TCM2280',
      extid: [extid],
      curve: chanel_f,
    };
    let res = await historyApi.getgraphData(graphParam);
    //绘制2D板形图曲线-长度序列
    if (Array.isArray(res.data.data.curve[0][str]) && res.data.data.curve[0][str].length > 0) {
      echart_singleChanel(res.data.data.curve[0][str], str, 'app_chanel');
    } else {
      echarts_no('app_chanel');
    }
  }

  function echart_singleChanel(data: any, title: any, id: any) {
    var need_x11 = [];
    var need_y11 = data;
    for (let i = 0; i < data.length; i++) {
      need_x11.push(i + 1);
    }
    var myChart = echarts.init(document.getElementById(id));
    var option = {
      title: {
        text: title,
        textStyle: {
          fontSize: 14,
          color: '#222',
        },
      },
      color: 'yellow',
      toolbox: toolbox,
      tooltip: {
        trigger: 'axis',
        textStyle: {
          color: '#222',
          fontSize: 14,
        },
      },
      grid: {
        left: '3%',
        right: '5%',
        top: '15%',
        bottom: '18%',
        containLabel: true,
      },
      xAxis: {
        axisLine: {
          lineStyle: {
            color: '#888',
          },
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dotted',
            color: '#ccc',
          },
        },
        nameTextStyle: {
          fontSize: 14,
          color: '#222',
        },
        name: '(m)',
        type: 'category',
        data: need_x11,
        axisLabel: {
          color: '#222',
          fontSize: 14,
        },
      },
      yAxis: [
        {
          scale: true,
          axisLine: {
            lineStyle: {
              color: '#888',
            },
          },
          type: 'value',
          name: '',
          axisLabel: {
            formatter: '{value}',
            color: '#222',
            fontSize: 14,
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dotted',
              color: '#ccc',
            },
          },
        },
      ],
      series: [
        {
          name: '',
          type: 'line',
          data: need_y11.map((value: any) => value / 20),
        },
      ],
    };
    myChart.clear();
    myChart.setOption(option);
  }

  // 无数据时：展示暂无数据
  function echarts_no(e: any, height = 400) {
    console.log('e' + e);
    const dom = document.getElementById(e);
    if (dom != null) {
      dom.innerHTML = '暂无数据';
      dom.style.cssText = 'text-align:center; color: #999; border: none;line-height:' + height + 'px';
      dom.removeAttribute('_echarts_instance_');
    }
  }

  // 销毁所有图表实例
  const disposeCharts = () => {
    // 销毁所有可能的图表实例
    const chartIds = ['app11', 'app_chanel', 'app5', 'app_tilt', 'app7', 'app4', 'app_tension'];
    chartIds.forEach((id) => {
      const dom = document.getElementById(id);
      if (dom) {
        const chart = echarts.getInstanceByDom(dom);
        if (chart) {
          chart.dispose();
        }
      }
    });
  };

  // 监听弹窗关闭事件，确保销毁图表
  const handleDialogClose = () => {
    disposeCharts();
  };

  // 监听窗口大小变化，调整图表
  const handleResize = () => {
    // 调整所有图表大小
    const chartIds = ['app11', 'app_chanel', 'app5', 'app_tilt', 'app7', 'app4', 'app_tension'];
    chartIds.forEach((id) => {
      const dom = document.getElementById(id);
      if (dom) {
        const chart = echarts.getInstanceByDom(dom);
        if (chart) {
          chart.resize();
        }
      }
    });
  };

  const getGradeClassByScore = (score: number) => {
    if (score === null || score === undefined || isNaN(score)) return '-';
    if (score >= 1 && score <= 2) return 'grade-b';
    if (score >= 2 && score <= 3) return 'grade-c';
    if (score >= 3) return 'grade-d';
    return 'grade-a';
  };

  const getGradeLetterByScore = (score: number) => {
    if (score === null || score === undefined || isNaN(score)) return '-';
    if (score >= 1 && score <= 2) return 'B';
    if (score >= 2 && score <= 3) return 'C';
    if (score >= 3) return 'D';
    return 'A';
  };

  // 新增张力差单独曲线
  async function findTensionChart(extid: any) {
    let params = ['tcm_s4s5_ten_diff'];
    const graphParam = {
      line: 'TCM2280',
      extid: [extid],
      curve: params,
    };
    const response = await historyApi.getgraphData(graphParam);
    if (response.data.data.curve[0]) {
      echart_tension(response.data.data.curve[0]);
    } else {
      echarts_no('app_tension');
    }
  }

  function echart_tension(obj: any) {
    let fakeArr = Array.from({ length: 20 }, (_, i) => i + Math.random());
    let tcm_s4s5_ten_diff = Array.isArray(obj.tcm_s4s5_ten_diff) && obj.tcm_s4s5_ten_diff.length > 0 ? obj.tcm_s4s5_ten_diff : fakeArr;
    var arrlength = [];
    for (let i = 1; i <= tcm_s4s5_ten_diff.length; i++) {
      arrlength.push(i);
    }
    var myChart = echarts.init(document.getElementById('app_tension'));
    var option = {
      title: {
        text: '5机架张力差',
        textStyle: {
          fontSize: 14,
          color: '#222',
          fontStyle: 'normal',
          fontWeight: 'bold',
        },
      },
      tooltip: { trigger: 'axis' },
      grid: { left: '3%', right: '6%', bottom: '8%', containLabel: true },
      legend: {
        x: 'center',
        data: ['5机架张力差'],
        textStyle: { fontSize: 12, color: '#222' },
        icon: 'roundRect',
      },
      toolbox: toolbox,
      dataZoom: [
        { type: 'slider', show: true, xAxisIndex: [0], start: 0, end: 100 },
        { type: 'inside', xAxisIndex: [0], start: 0, end: 100 },
      ],
      xAxis: {
        type: 'category',
        boundaryGap: false,
        axisLabel: { show: true, color: '#222', fontSize: 14 },
        axisLine: { lineStyle: { color: '#222' } },
        splitLine: { show: true, lineStyle: { type: 'dotted' } },
        data: arrlength,
      },
      yAxis: {
        name: '单位: kN',
        type: 'value',
        scale: true,
        splitLine: { show: true, lineStyle: { type: 'dotted' } },
        axisLabel: { formatter: '{value}', color: '#222', fontSize: 14 },
        axisLine: { lineStyle: { color: '#222' } },
      },
      series: [
        {
          name: '5机架张力差',
          type: 'line',
          smooth: true,
          data: tcm_s4s5_ten_diff,
        },
      ],
    };
    myChart.clear();
    myChart.setOption(option);
  }
</script>

<style scoped>
  .prdp-outer {
    width: 100vw;
    height: 100vh;
    display: flex;
    flex-direction: column;
    background: linear-gradient(to top, #eaf1fb 0%, #2c69e8 100%);
    overflow: hidden;
  }
  .prdp-main {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
    padding: 20px;
  }
  .prdp-table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
  }
  .el-table {
    flex: 1;
    height: 100% !important;
    min-height: 0;
  }
  .prdp-pagination {
    margin-top: 10px;
  }
  .prdp-title-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .prdp-title-bar h2 {
    margin: 0;
    color: #333;
  }

  .prdp-status-indicators {
    display: flex;
    gap: 20px;
  }

  .prdp-status-item {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .prdp-status-text {
    color: #333;
    font-size: 14px;
  }

  .prdp-status-dot {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background-color: #67c23a;
    display: inline-block;
  }

  .prdp-search-container {
    margin-bottom: 20px;
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }

  .prdp-pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  /* 等级指示器样式 */
  .prdp-grade-indicator {
    display: flex;
    justify-content: center;
  }

  .prdp-grade-a {
    color: #67c23a;
    font-weight: bold;
  }

  .prdp-grade-b {
    color: #409eff;
    font-weight: bold;
  }

  .prdp-grade-c {
    color: #e6a23c;
    font-weight: bold;
  }

  .prdp-grade-d {
    color: #f56c6c;
    font-weight: bold;
  }

  .prdp-rate-indicator {
    text-align: center;
  }

  /* 详情弹窗样式 */
  :deep(.prdp-detail-dialog .el-dialog__header) {
    background-color: #1a237e;
    padding: 10px 20px;
    margin-right: 0;
  }

  :deep(.prdp-detail-dialog .el-dialog__title) {
    color: #fff;
    font-size: 16px;
  }

  :deep(.prdp-detail-dialog .el-dialog__headerbtn .el-dialog__close) {
    color: #fff;
  }

  :deep(.prdp-detail-dialog .el-dialog__body) {
    padding: 0;
  }

  .prdp-detail-container {
    padding: 15px;
    max-height: 80vh;
    overflow-y: auto;
  }

  .prdp-coil-info {
    margin-bottom: 20px;
  }

  :deep(.prdp-coil-info .el-descriptions__label) {
    background-color: #f5f7fa;
    color: #333;
  }

  .prdp-charts-container {
    margin-bottom: 20px;
  }

  .prdp-charts-row {
    display: flex;
    margin-bottom: 20px;
    gap: 20px;
  }

  .prdp-chart-item {
    flex: 1;
    min-height: 280px;
    border: 1px solid #e6e6e6;
    border-radius: 4px;
    overflow: hidden;
  }

  .prdp-chart-title {
    padding: 10px;
    font-size: 14px;
    font-weight: bold;
    color: #333;
    background-color: #f5f7fa;
    border-bottom: 1px solid #e6e6e6;
  }

  .prdp-chart {
    height: 240px;
  }

  .prdp-shape-view {
    border: 1px solid #e6e6e6;
    border-radius: 4px;
    overflow: hidden;
  }

  .prdp-shape-tabs {
    display: flex;
    background-color: #f5f7fa;
  }

  .prdp-shape-tab {
    padding: 10px 15px;
    cursor: pointer;
    font-size: 14px;
    color: #333;
  }

  .prdp-shape-tab-active {
    color: #1a237e;
    border-bottom: 2px solid #1a237e;
    font-weight: bold;
  }

  .prdp-shape-content {
    padding: 10px;
    min-height: 200px;
    background-color: #fff;
  }

  .prdp-shape-img {
    width: 100%;
    height: auto;
    display: block;
  }

  .grade-dot {
    display: inline-flex;
    align-items: center;
    gap: 2px;
    cursor: pointer;
    height: 26px;
  }

  .grade-letter {
    font-size: 14px;
    font-weight: bold;
    line-height: 26px;
  }

  .grade-circle {
    font-size: 26px;
    line-height: 1;
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 4px;
  }

  .grade-a {
    color: #67c23a;
  }
  .grade-b {
    color: #409eff;
  }
  .grade-c {
    color: #e6a23c;
  }
  .grade-d {
    color: #f56c6c;
  }

  .rate-container {
    display: inline-flex;
    align-items: center;
    gap: 4px;
  }

  .rate-dot {
    font-size: 26px;
    line-height: 1;
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 4px;
  }

  .rate-text {
    font-size: 14px;
    line-height: 26px;
  }

  .rate-dot-red {
    color: #f56c6c;
  }
  .rate-dot-green {
    color: #67c23a;
  }
</style>
